<!--
* @author luguoxiang
* @date 2021-09-07
* 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <slot :loading="loading" :options="options">
    <component :is="props.component || 't-cascader'" v-loading="loading" :options="options" v-bind="$attrs" />
  </slot>
</template>

<script lang="ts">
export default {
  name: 'RegionSelect',
};
</script>
<script lang="ts" setup>
import { Component as ComponentDef, ref } from 'vue';
import api from './api';

interface Props {
  /**
   * 数据处理器
   */
  handler?(res: any[]): any[];
  /**
   * 前面的选项
   */
  prepend?: Function | Object[] | Object;
  /**
   * 后面的选项
   */
  append?: Function | Object[] | Object;
  /**
   * 搜索字段或true，为字符串时远程搜索具体字段，为true时本地筛选label
   */
  search?: boolean;
  /**
   * 使用的组件(可以是组件引入对象或字符串（全局引入的）)
   */
  component?: ComponentDef | string;
}
const props = defineProps<Props>();

const loading = ref(false);
const options = ref([]);

function getDataArray(data) {
  if (typeof data === 'function') {
    data = data();
  }
  if (Array.isArray(data)) {
    return data;
  }
  return [data];
}

api
  .tree()
  .then((res) => {
    if (typeof props.handler === 'function') {
      res = props.handler(res);
    }
    if (props.prepend) {
      res = getDataArray(props.prepend).concat(res);
    }
    if (props.append) {
      res = res.concat(getDataArray(props.append));
    }
    options.value = res;
  })
  .finally(() => {
    loading.value = false;
  });
loading.value = true;
</script>
